package config

import (
	"fmt"
	"io/ioutil"
	"gopkg.in/yaml.v2"
)
//配置文件解析 prome-shard.yml
type Config struct {
	ShardService []*ShardService     `yaml:"shard_service"`
	ConsulServer *ConsulServerConfig `yaml:"consul_server"`
	RpcAddr      string              `yaml:"rpc_addr"`
	HttpAddr     string              `yaml:"http_addr"`
}

//- name:   scrape_prometheus_get_alert
//  file_type: yaml
//  desc: alert rule文件
//  nodes:
//   - 192.168.3.200
//   - 192.168.3.201
//
//  port: 9090
//  dest_sd_file_name: file_sd_by_prome_shared.yaml
//  yaml_path: ./copy_file_and_reload_prome.yaml
type ShardService struct {
	Name     string `yaml:"name"`
	FileType string `yaml:"file_type"`

	Desc           string   `yaml:"desc"`
	DestSdFileName string   `yaml:"dest_sd_file_name"`
	YamlPath       string   `yaml:"yaml_path"`
	Nodes          []string `yaml:"nodes"`
	Port           int      `yaml:"port"`
}

//consul_server:
//  addr: 192.168.3.200:8500
//  username:
//  password:
type ConsulServerConfig struct {
	Addr     string `yaml:"addr,omitempty"`
	Username string `yaml:"username,omitempty"`
	Password string `yaml:"password,omitempty"`
}

func Load(s string) (*Config, error) {
	cfg := &Config{}

	err := yaml.Unmarshal([]byte(s), cfg)

	if err != nil {
		return nil, err
	}

	return cfg, nil
}

func LoadFile(filename string) (*Config, error) {
	content, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}

	cfg, err := Load(string(content))
	if err != nil {
		fmt.Printf("[parsing YAML file errr...][error:%v]", err)
		return nil, err
	}
	return cfg, nil
}
